import os
import glob
import re
import pandas as pd
import tensorflow.compat.v1 as tf

class ImageReader(object):
  """Helper class that provides TensorFlow image coding utilities."""
 
  def __init__(self):
    # Initializes function that decodes RGB JPEG data.
    self._decode_jpeg_data = tf.placeholder(dtype=tf.string)
    self._decode_jpeg = tf.image.decode_jpeg(self._decode_jpeg_data, channels=3)
 
  def read_image_dims(self, sess, image_data):
    image = self.decode_jpeg(sess, image_data)
    return image.shape[0], image.shape[1]
 
  def decode_jpeg(self, sess, image_data):
    image = sess.run(self._decode_jpeg,
                     feed_dict={self._decode_jpeg_data: image_data})
    #pdb.set_trace()
    assert len(image.shape) == 3
    assert image.shape[2] == 3
    return image

def _get_pn_imgPaths(dataset_dir, split_name = None):
  #获取文件所在路径
  split_dir = dataset_dir
  if split_name:
    split_dir = os.path.join(dataset_dir, split_name)
  paths = []
  #遍历目录下的所有图片
  for filename in os.listdir(split_dir):
      #获取文件的路径
      file_path = os.path.join(split_dir, filename)
      if file_path.endswith("jpg") and os.path.exists(file_path):
          paths.append(file_path)
  return paths

def pn_to_csv(path):
    img_paths = _get_pn_imgPaths(path)
    xml_list = []
    with tf.Graph().as_default():
        image_reader = ImageReader()
        with tf.Session('') as sess:
            for filename in img_paths:
                #读取图片,将图片数据读取为bytes
                image_data = tf.gfile.FastGFile(filename, 'rb').read()
                #获取图片的高和宽
                height, width = image_reader.read_image_dims(sess, image_data)
                #获取路径中的图片名称
                img_name = os.path.basename(filename)
                #获取图片的类别
                class_name = img_name.split("_")[0]
                if re.match(r'(.*)positive(.*?)', filename, re.M|re.I):
                  class_name = 'positive'
                elif re.match(r'(.*)negative(.*?)', filename, re.M|re.I):
                  class_name = 'negative'
                value = (img_name,
                          width,
                          height,
                          class_name,
                          int(1),
                          int(1),
                          int(width - 2),
                          int(height - 2)
                        )
                xml_list.append(value)
    column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
    xml_df = pd.DataFrame(xml_list, columns=column_name)
    return xml_df

def main(image_path, output_path):
    xml_df = pn_to_csv(image_path)
    outputs = 'labels.csv'
    if output_path:
      outputs = output_path
    xml_df.to_csv(outputs, index=None)
    print('Successfully converted xml to csv.')

if __name__ == '__main__':
    # image_path = os.path.join(os.getcwd(), 'annotations')
    train_image_path = '../dataset/Concrete Crack Images for Classification/train'
    main(train_image_path, '../dataset/Concrete Crack Images for Classification/train.csv')
    eval_image_path = '../dataset/Concrete Crack Images for Classification/eval'
    main(eval_image_path, '../dataset/Concrete Crack Images for Classification/eval.csv')
